package cn.com.yang.thread;

import java.util.Iterator;
import java.util.concurrent.Exchanger;

/**
 * 两个线程间数据交换
 * TODO
 * @author yangyijin
 * @since 2024年1月8日-上午8:52:12
 */
public class TestExchanger {

	public static void main(String[] args) {
		try {
			test1();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private static void test1() throws InterruptedException {
		Exchanger exchanger = new Exchanger();
		Thread t1 = new Thread(()->{
			try {
				Object data = "--待交换数据AAA";
				System.out.println(Thread.currentThread().getName()+data);
				//开始交换数据
				data = exchanger.exchange(data);
				//带超时的交换	
//				data = exchanger.exchange(data, 30000L, TimeUnit.MICROSECONDS);
				System.out.println(Thread.currentThread().getName()+data);
			} catch (Exception e) {
				// TODO: handle exception
			}
		});
		t1.start();
		//线程中断
		Thread.sleep(3000L);
		t1.interrupt();
		
		new Thread(()->{
			try {
				Object data = "--待交换数据BBB";
				System.out.println(Thread.currentThread().getName()+data);
				//开始交换数据
				data = exchanger.exchange(data);
				System.out.println(Thread.currentThread().getName()+data);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}).start();
	}
	
	private static void test2() {
		Exchanger exchanger = new Exchanger<>();
		for(int i=1;i<=10;i++) {
			Integer data = i;
			new Thread(()->{
				try {
					Object exdata = exchanger.exchange(data);
					System.out.print(Thread.currentThread().getName()+"-"+exdata);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}).start();
		}
		
	}
}
